package com.bourne.util;

import com.bourne.constant.NumConstant;
import com.bourne.constant.StringConstant;
import com.bourne.enums.BizCodeEnum;
import com.bourne.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * JWT的思想：去中心化、无状态化
 * @PROJECT_NAME:
 * @DATE: 2021/3/30 20:55
 */
@Slf4j
public class JwtUtil {

    /**
     * 根据用户信息，生成令牌
     * @param user
     * @return
     */
    public static String geneJsonWebToken(LoginUser user) {
        if (user == null){
            throw new NullPointerException("loginUser对象不能为空");
        }
        String token = Jwts.builder().setSubject(StringConstant.SYSTEM_SUBJECT)
                //.claim("head_img", user.getHeadImg())
                .claim("id", user.getId())
                .claim("name", user.getName())
                .claim("phone", user.getPhone())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + NumConstant.TOKEN_EXPIRE))
                .signWith(SignatureAlgorithm.HS256, StringConstant.SYSTEM_SECRET).compact();
        token = StringConstant.TOKEN_PREFIX + token;
        try {
            String[] split = StringUtils.split(token, StringConstant.POINT);
            String data = RSAUtils.encrypt(split[NumConstant.ONE].substring(NumConstant.ZERO, NumConstant.ONE_HUNDRED), StringConstant.DEFAULT_RSA_PUB_KEY)
                    + RSAUtils.encrypt(split[NumConstant.ONE].substring(NumConstant.ONE_HUNDRED), StringConstant.DEFAULT_RSA_PUB_KEY);
            return split[0] + "." + data + "." + split[2];
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 校验token的方法
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token, HttpServletResponse response) {
        try {
            String[] split = StringUtils.split(token, StringConstant.POINT);
            String data = RSAUtils.decrypt(split[NumConstant.ONE].substring(NumConstant.ZERO, NumConstant.RAS_SPILT_LENGTH), StringConstant.DEFAULT_RSA_PRI_KEY)
                    + RSAUtils.decrypt(split[NumConstant.ONE].substring(NumConstant.RAS_SPILT_LENGTH), StringConstant.DEFAULT_RSA_PRI_KEY);
            if (StringUtils.isBlank(data)) {
                return null;
            }
            token = split[NumConstant.ZERO] + "." + data + "." + split[NumConstant.TWO];
            final Claims claims = Jwts.parser()
                    .setSigningKey(StringConstant.SYSTEM_SECRET)
                    .parseClaimsJws(token.replace(StringConstant.TOKEN_PREFIX, "")).getBody();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }
}
